package com.todo.event.activity.application.core.frequency;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.utils.DateUtils;
import com.todo.component.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Set;

/**
 * @author azhebuxing
 * @date 2025/1/8 22:57
 * @description
 */
@Slf4j
@Component
public class FrequencyHelper {

    private static final String GENERAL_FREQUENCY_CONF_KEY = "general:frequency:conf:key:%s";
    private static final String EXECUTE_ITEM_RECORD_KEY = "general:frequency:execute:key:%s:%s";

    @Resource
    private RedisService redisService;

    /**
     * 保存频次配置
     *
     * @param activityId
     * @param frequencyConf
     */
    public void saveFrequencyConf(Long activityId, FrequencyConf frequencyConf) {
        String key = String.format(GENERAL_FREQUENCY_CONF_KEY, activityId);
        redisService.set(key, JSONObject.toJSONString(frequencyConf), DateUtils.between(new Date(), frequencyConf.getActivityEndTime()).toMillis());
        log.info("FrequencyHelper#saveFrequencyConf 保存频次配置完成，activityId:{},frequencyConf：{}", activityId, JSONObject.toJSONString(frequencyConf));
    }

    /**
     * 校验并重建频次配置
     *
     * @param activityId
     * @param frequencyConf
     */
    public void checkAndReBuildFrequencyConf(Long activityId, FrequencyConf frequencyConf) {
        String key = String.format(GENERAL_FREQUENCY_CONF_KEY, activityId);
        Boolean hasKey = redisService.hasKey(key);
        if (hasKey) {
            return;
        }
        log.warn("FrequencyHelper#checkAndReBuildFrequencyConf 校验并重建频次配置，当前数据为空，重建配置 activityId:{},frequencyConf：{}", activityId, JSONObject.toJSONString(frequencyConf));
        redisService.set(key, JSONObject.toJSONString(frequencyConf), DateUtils.between(new Date(), frequencyConf.getActivityEndTime()).toMillis());
    }

    /**
     * 保存执行记录
     *
     * @param activityId
     * @param userId
     * @param operateTime
     * @return
     */
    public Boolean saveExecuteItemRecord(Long activityId, Long userId, Date operateTime) {
        String confKey = String.format(GENERAL_FREQUENCY_CONF_KEY, activityId);
        if (!redisService.hasKey(confKey)) {
            return false;
        }
        String cacheData = redisService.get(confKey);
        FrequencyConf frequencyConf = JSONObject.parseObject(cacheData, FrequencyConf.class);
        String key = String.format(EXECUTE_ITEM_RECORD_KEY, activityId, userId);
        //当前数量比对
        Long currentCount = redisService.sSize(key);
        int removeCount = 0;
        if (currentCount >= frequencyConf.getCount()) {
            //剔除无用数据
            Set<String> strings = redisService.sMembers(key);
            //当前时间减去间隔时间再比较
            LocalDateTime localDateTime = DateUtils.dateToLocalDateTime(operateTime);
            LocalDateTime calDate = localDateTime.plusDays(-frequencyConf.getDay());
            for (String string : strings) {
                Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, string);
                if (date.before(DateUtils.toDate(calDate))) {
                    redisService.sRemove(key, string);
                    removeCount++;
                }
            }
            if (removeCount == 0) {
                return false;
            }
        }

        redisService.sAdd(key, DateUtils.between(operateTime, frequencyConf.getActivityEndTime()).toMillis(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, operateTime));
        log.info("FrequencyHelper#saveExecuteItemRecord 保存执行记录完成，activityId:{},userId：{},operateTime：{}", activityId, userId, DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, operateTime));
        return true;
    }

    /**
     * 检查记录数量是否满足
     *
     * @param activityId
     * @param userId
     * @return
     */
    public Boolean checkRecordCount(Long activityId, Long userId,Date operateTime) {
        String confKey = String.format(GENERAL_FREQUENCY_CONF_KEY, activityId);
        if (!redisService.hasKey(confKey)) {
            return false;
        }
        String cacheData = redisService.get(confKey);
        FrequencyConf frequencyConf = JSONObject.parseObject(cacheData, FrequencyConf.class);
        String key = String.format(EXECUTE_ITEM_RECORD_KEY, activityId, userId);
        //当前数量比对
        Long currentCount = redisService.sSize(key);
        int removeCount = 0;
        if (currentCount >= frequencyConf.getCount()) {
            //剔除无用数据
            Set<String> strings = redisService.sMembers(key);
            //当前时间减去间隔时间再比较
            LocalDateTime localDateTime = DateUtils.dateToLocalDateTime(operateTime);
            LocalDateTime calDate = localDateTime.plusDays(-frequencyConf.getDay());
            for (String string : strings) {
                Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, string);
                if (date.before(DateUtils.toDate(calDate))) {
                    redisService.sRemove(key, string);
                    removeCount++;
                }
            }
            if (removeCount == 0) {
                return false;
            }
        }
        return true;
    }
}
